//
//  ZWTools.m
//  cnwan
//
//  Created by LY-Coder on 2017/6/27.
//  Copyright © 2017年 xchuang. All rights reserved.
//

#import "ZWTools.h"

@implementation ZWTools
+(UIColor *)colorWithHexString: (NSString *)hexColor
{
    NSString *cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
+ (NSString *)ToHex:(uint16_t)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    uint16_t ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    if (str.length < 2) {
        str =[NSString stringWithFormat:@"0%@",nLetterValue];
    }
    return str;
}
+(UIImage *)createImageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);  //图片尺寸
    UIGraphicsBeginImageContext(rect.size); //填充画笔
    CGContextRef context = UIGraphicsGetCurrentContext(); //根据所传颜色绘制
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect); //联系显示区域
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); // 得到图片信息
    UIGraphicsEndImageContext(); //消除画笔
    return image;
}
//json 转化字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    if(err) {
        
//        NSLog(@"json解析失败：%@",err);
        return nil;
        
    }
    return dic;
}
+(NSArray*)ChangeTimeArray:(NSString *)startTime endTime:(NSString*)endTime {
    
//    NSLog(@"---+%@",startTime);
    
    long startT= [self timeChange:startTime];
    long endT = [self timeChange:endTime];
    return [self timeArrayInt:startT endTime:endT];
}
//显示x月x日
+(NSString *)showMonthAndDayWith:(NSString *)dateStr{
    //格式化日期
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    NSDate* date = [formatter dateFromString:dateStr];
    formatter.dateFormat = @"MM月dd日";
    NSString *timeStr = [formatter stringFromDate:date];
    return timeStr;
}
+(long)timeChange:(NSString*)endTime {
    
    //传过来的
    NSString* timeStr = endTime;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
    long t  = [date timeIntervalSince1970];
    
    return t;
    
}
+(NSArray*)timeArrayInt:(NSInteger )startT endTime:(NSInteger)endT {
    
    long t = endT - startT;
    NSInteger t1 = t/86400;   // 商   天
    NSInteger t2 = t%86400;    //余数(秒)
    NSInteger t3 = t2/3600;    // 小时
    NSInteger t4 = t2%3600;    //余数(秒)
    NSInteger t5 = t4/60;      // 得到分
    
    NSString * day = [NSString stringWithFormat:@"%ld",t1];
    NSString * hour = [NSString stringWithFormat:@"%ld",t3];
    NSString * min = [NSString stringWithFormat:@"%ld",t5];
    //    NSLog(@"---+++++++剩余%zd天%zd小时%zd分钟",t1,t3,t5);
    NSMutableArray * TimeArray = [NSMutableArray array];
    
    if ([day integerValue] <= 0) {
        day = @"0";
    }
    if ([hour integerValue] <= 0) {
        hour = @"0";
    }
    if ([min integerValue] <= 0) {
        min = @"0";
    }
    
    [TimeArray addObject:day];
    [TimeArray addObject:hour];
    [TimeArray addObject:min];
    
    
    return TimeArray;
}

+(id)initWithNavigationBar {
    //设置tint颜色
//    [[UINavigationBar appearance] setTintColor:COLOR_DARK_GRAY];
//    //设置导航栏背景色
//    [[UINavigationBar appearance] setBarTintColor:COLOR_MAIN];
//    //设置导航栏为不透明
//    [[UINavigationBar appearance] setTranslucent:NO];
    //TabBar选中图标的颜色,
    [[UITabBar appearance] setTintColor:COLOR_LOGIN_BLUE];
    //设置tabbar为不透明
//    [UITabBar appearance].translucent = NO;
    //设置表格的背景色
//    [[UITableView appearance] setBackgroundColor:COLOR_MAIN];
    [[UITableView appearance] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
//    [[UITableViewCell appearance] setSelectionStyle:UITableViewCellSelectionStyleNone];
    return nil;
}

+(id)objectForKey:(NSString *)defaultName
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName];
}

+(void)setObject:(id)value forKey:(NSString *)defaultName
{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
//手机号验证
+ (BOOL)validateMobile:(NSString *)mobile
{
    // 130-139  150-153,155-159  180-189  145,147  170,171,173,176,177,178,190
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(19[0])|(17[013678]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

//判断是否有emoji
+(BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar high = [substring characterAtIndex: 0];
                                
                                // Surrogate pair (U+1D000-1F9FF)
                                if (0xD800 <= high && high <= 0xDBFF) {
                                    const unichar low = [substring characterAtIndex: 1];
                                    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                    
                                    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                        returnValue = YES;
                                    }
                                    
                                    // Not surrogate pair (U+2100-27BF)
                                } else {
                                    if (0x2100 <= high && high <= 0x27BF){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
//没有内容的展示
+(UILabel *)warnNoContentLabelView:(NSString *)str{
    
    UILabel *warnMessage = [[UILabel alloc]init];
    warnMessage.text = str;
    warnMessage.textColor = COLOR_LOGIN_BLUE;
    warnMessage.textAlignment = NSTextAlignmentCenter;
    
    return warnMessage;
}
//没有内容偏下的展示
+(UIView *)warnNoContentLabelBottomView:(NSString *)str{
    UIView *backView =[[UIView alloc]init];
    backView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H);

    UILabel *warnMessage = [[UILabel alloc]init];
    warnMessage.text = str;
    warnMessage.font = H4;
    warnMessage.frame = CGRectMake(0, SCREEN_H - 150, SCREEN_W, 50);
    warnMessage.textColor = COLOR_LOGIN_BLUE;
    warnMessage.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:warnMessage];
    
    return backView;
}
//没有内容带图的展示
+(UIView *)warnNoContentWithImag:(NSString *)imagStr andLoginBtnHidden:(BOOL)hidden target:(nullable id)target withSEL:(SEL _Nullable )action{
    UIView *backView =[[UIView alloc]init];
    backView.backgroundColor = COLOR_MAIN;
    
    UIImageView *warnMessage = [[UIImageView alloc]init];
    warnMessage.image = [UIImage imageNamed:imagStr];
    warnMessage.frame = CGRectMake(Scare_Width(69),Scare_Width(280)-Scare_Width(237)*0.517, Scare_Width(237), Scare_Width(237)*0.517);
    [backView addSubview:warnMessage];
    
    if (hidden == YES) {
        backView.frame = CGRectMake(0, Scare_Width(280), SCREEN_W, Scare_Width(237)*0.517);

    }else{
        backView.frame = CGRectMake(0, Scare_Width(280), SCREEN_W, Scare_Width(237)*0.517 + Scare_Width(68));

        UIButton *loginBtn =[[UIButton alloc]init];
        loginBtn.frame = CGRectMake(0, Scare_Width(308), Scare_Width(150), Scare_Width(40));
        loginBtn.centerX = backView.centerX;
        loginBtn.layer.cornerRadius = Scare_Width(10);
        [loginBtn setBackgroundColor:COLOR_RED];
        [loginBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        loginBtn.titleLabel.font = H4;
        [loginBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        [loginBtn setTitle:@"点击登录" forState:UIControlStateNormal];
        [backView addSubview:loginBtn];
    }
    return backView;
}
//设置不同字体颜色
+(void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    
    label.attributedText = str;
}
//自定义上下文格式button内容
+(NSMutableAttributedString *)setUpTitle:(NSString *)upStr withBottomStr:(NSString *)botStr  withUpFont:(NSInteger)upFont withBotFont:(NSInteger)botFont withTitleColor:(UIColor *)upColor withBottomColor:(UIColor *)botColor{
    NSString *t0 = upStr;
    NSString *t1 = botStr;
    NSDictionary *attrTitleDict0 = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:upFont],NSForegroundColorAttributeName: upColor};
    NSDictionary *attrTitleDict1 = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:botFont],NSForegroundColorAttributeName: botColor};
    
    NSAttributedString *attrStr0 = [[NSAttributedString alloc] initWithString: [t0 substringWithRange: NSMakeRange(0, t0.length)] attributes: attrTitleDict0];
    NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString: [t1 substringWithRange: NSMakeRange(0, t1.length)] attributes: attrTitleDict1];
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithAttributedString: attrStr0];
    [attributedStr appendAttributedString:attrStr1];
    return attributedStr;
}

/**
 * 图片压缩到指定大小
 * @param targetSize 目标图片的大小
 * @param sourceImage 源图片
 * @return 目标图片
 */
+ (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        ZWLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    return newImage;
}
@end
